<template>
  <div class="following_list" v-loading="loading.tempDetail" element-loading-text="模板正在加载中...预计需要5-10秒，请耐心等待~">
    <searchBox>
      <template #yyxbread>
        <div style="display: flex; align-items: center">
          <el-icon>
            <Location />
          </el-icon>
          <span class="f12 ml10 mr10">当前位置：</span>
          <el-breadcrumb separator="/" class="f14">
            <el-breadcrumb-item>预算报价</el-breadcrumb-item>
            <el-breadcrumb-item class="active">预算报价明细</el-breadcrumb-item>
          </el-breadcrumb>
        </div>
      </template>
    </searchBox>
    <div class="content">
      <div
        class="fixed-fold-btn"
        :class="{ 'fold-left': isFold }"
        type="primary"
        title="展开/收起左侧内容"
        @click="isFold = !isFold"
      ></div>
      <div class="content_box" :class="{ 'fold-wrap': isFold }">
        <div class="content_left">
          <div class="left_info" v-loading="loading.baseInfo">
            <div class="info_title">基础信息</div>
            <div class="info_detail">
              <div>客户名称：</div>
              <el-tooltip effect="dark" :content="customerName">
                <div class="detail_text">{{ customerName || "--" }}</div>
              </el-tooltip>
              <div>项目地址：</div>
              <el-tooltip effect="dark" :content="baseInfo.customerAddress">
                <div class="detail_text">{{ baseInfo.customerAddress || "--" }}</div>
              </el-tooltip>
              <div>户型：</div>
              <el-tooltip effect="dark" :content="baseInfo.customerSummary">
                <div class="detail_text">{{ baseInfo.customerSummary || "--" }}</div>
              </el-tooltip>
              <div>面积：</div>
              <el-tooltip effect="dark" :content="baseInfo.houseArea">
                <div class="detail_text">{{ baseInfo.houseArea || "--" }}</div>
              </el-tooltip>
              <div>设计师：</div>
              <el-tooltip effect="dark" :content="baseInfo.designUserName">
                <div class="detail_text">{{ baseInfo.designUserName || "--" }}</div>
              </el-tooltip>
            </div>
          </div>
          <div class="left_template">
            <div class="template_title">
              <div>模板信息</div>
              <el-button link style="color: #041830" @click="importTempFlag = true">
                导入模板
                <img class="ml5" src="@/assets/images/download-icon.png" />
              </el-button>
            </div>
            <div class="template_list" v-if="tempList.length > 0">
              <template v-for="item in tempList" :key="item.id">
                <div
                  :id="item.budgetId"
                  :class="`list_box ${item.budgetId === currTemp.budgetId ? 'active_box' : ''}`"
                  @click="changeCurrTemp(item)"
                  v-loading="loading.tempList"
                >
                  <div class="box_suffix" v-if="item.budgetType === 2">套餐</div>
                  <div class="box_suffix" v-if="item.budgetStatus === 1 && !item.contractId">已发起订单</div>
                  <div class="box_title jzt-flex-start" :title="item.budgetName">
                    <p class="text-over">{{ item.budgetName }}</p>
                    <img v-if="item.softDecorationStatus === 1" src="@/assets/images/ruanzhuang.png" width="36" alt="" />
                  </div>
                  <div class="box_content">
                    {{ item.updateTime }}
                    <el-popover placement="bottom" :width="70" trigger="hover">
                      <template #default>
                        <div class="operate_btns">
                          <el-button class="operate_btn" @click="editTemplate(item)" link v-if="item.disable !== 1">
                            编辑
                          </el-button>
                          <el-button class="operate_btn" @click="copyTemplate(item)" link>复制</el-button>
                          <el-button
                            v-if="((!item.budgetStatus && !item.contractId) || item.contractStatus === 4) && item.disable !== 1"
                            class="operate_btn"
                            @click="handleContract(item)"
                            link
                            >提交
                          </el-button>
                          <el-button
                            v-if="item.budgetStatus === 1 && item.contractStatus !== 4 && item.disable !== 1"
                            class="operate_btn"
                            @click="handleCloseContract(item)"
                            link
                            >关闭订单
                          </el-button>
                          <el-button
                            v-if="item.disable !== 1"
                            class="operate_btn"
                            type="danger"
                            @click="deleteTemplate(item)"
                            link
                            >删除
                          </el-button>
                        </div>
                      </template>
                      <template #reference>
                        <el-button type="primary" link>
                          <el-icon color="#86909c">
                            <MoreFilled />
                          </el-icon>
                        </el-button>
                      </template>
                    </el-popover>
                  </div>
                </div>
              </template>
            </div>
            <el-empty v-else description="暂无数据" />
          </div>
        </div>
        <div class="content_right">
          <templateDetail
            :tempDetail="tempDetail"
            :customDetail="baseInfo"
            :hasContract="hasContract"
            :nextPart="nextPart"
            :originLength="detailRES?.spaceList?.length"
            @refresh="
              () => {
                getTempDetail(false, false);
              }
            "
            @handleContract="handleContract"
            @handleEditContract="handleEditContract"
            @handleCloseContract="handleCloseContract"
          />
          <!-- <templateDetail
            v-if="!isEmpty(tempDetail)"
            v-model="tempDetail"
            :tempDetail="currTemp"
            :customDetail="baseInfo"
            :hasContract="hasContract"
            @refresh="getTempDetail"
            @handleContract="handleContract"
          />
          <el-empty style="height: 100%" v-else description="暂无数据" /> -->
        </div>
      </div>
    </div>

    <importTempDrawer v-if="importTempFlag" v-model="importTempFlag" :ys-id="queryId" @success="handleSuccessImport" />

    <editTemplateDialog
      v-if="editTemplateFlag"
      v-model="editTemplateFlag"
      :currTemp="currTemp"
      @success="successHandle('模版名称修改成功')"
    />

    <ActionSubmitDialog
      v-model:isOpen="deleteTemplateFlag"
      title="提醒"
      message="您正在删除导入的模板，请问是否继续当前操作？"
      submitBtnText="继续"
      @submit="deleteTemplateConfirm"
    />

    <contractModal
      v-if="contractModalFlag"
      v-model="contractModalFlag"
      :budgetDetail="tempDetail"
      :customDetail="baseInfo"
      :tempDetail="currTemp"
      @submit="contractHandle"
      :contractType="contractType"
    />

    <alertDialog v-if="alertDialogFlag" v-model="alertDialogFlag" :detail="alertDetail" @commit="submitApproval" />
    <!--  发起订单  -->
    <el-dialog v-model="orderVisible" title="发起订单" width="500" :before-close="handleClose">
      <el-form ref="formRef" style="max-width: 600px" :model="orderForm" label-width="auto" class="demo-dynamic">
        <el-form-item prop="receivingName" label="收货人" :rules="[{ required: true, message: '请输入', trigger: 'blur' }]">
          <el-input v-model="orderForm.receivingName" disabled />
        </el-form-item>
        <el-form-item
          prop="receivingMobile"
          label="手机"
          :rules="[
            {
              required: true,
              message: '请输入',
              trigger: 'blur'
            }
          ]"
        >
          <el-input v-model="orderForm.receivingMobile" disabled />
        </el-form-item>
        <el-form-item
          prop="receivingAreaIds"
          label="收货地址"
          :rules="[
            {
              required: true,
              message: '请输入',
              trigger: 'blur'
            }
          ]"
        >
          <!-- 省市区级联选择 -->
          <el-cascader
            v-model="orderForm.receivingAreaIds"
            :options="area"
            :props="{
              expandTrigger: 'hover',
              value: 'id',
              label: 'name'
            }"
            style="width: 100%"
            @change="areaChange"
          />
        </el-form-item>
        <el-form-item
          prop="receivingAddress"
          label="详细地址"
          :rules="[
            {
              required: true,
              message: '请输入详细地址',
              trigger: 'blur'
            }
          ]"
        >
          <el-input v-model="orderForm.receivingAddress" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer" style="text-align: center">
          <el-button @click="handleClose" class="space_param_btn" style="background: #f2f3f5; color: black">取消 </el-button>
          <el-button type="primary" @click="handleConfirm" class="space_param_btn" style="background: #424e66"> 确认 </el-button>
        </div>
      </template>
    </el-dialog>
    <!--  合同类型  -->
    <el-dialog v-model="typeVisible" title="合同类型" width="500">
      <div style="display: flex; align-items: center">
        <span style="color: #ff3333">*</span>
        <span style="flex-shrink: 0; margin-right: 10px">合同类型</span>
        <el-select v-model="contractType" placeholder="请选择合同类型">
          <el-option
            v-for="item in contractTypeList"
            :key="item.contractTypeId"
            :label="item.contractTypeName"
            :value="item.contractTypeId"
          />
        </el-select>
      </div>
      <template #footer>
        <div class="dialog-footer" style="text-align: center">
          <el-button @click="typeVisible = false" class="space_param_btn" style="background: #f2f3f5; color: black"
            >取消
          </el-button>
          <el-button type="primary" @click="handleSubmit" class="space_param_btn" style="background: #424e66"> 确认 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { computed, nextTick, onMounted, provide, ref } from "vue";
import searchBox from "@/views/home/components/search";
import { useRoute } from "vue-router";
import importTempDrawer from "./components/importTempDrawer.vue";
import templateDetail from "./components/templateDetail.vue";
import editTemplateDialog from "./components/editTemplateDialog.vue";
import ActionSubmitDialog from "@/components/ActionSubmitDialog";
import contractModal from "./components/contractModal.vue";
import alertDialog from "./components/alertDialog.vue";
import { isEmpty } from "lodash";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  checkgrossProfitRate,
  closeOrder,
  commitApproval,
  copyBudgetQuotation,
  createContract,
  delBudgetQuotation,
  getArea,
  getBudgetDetail,
  getContractTypeList,
  getCustomDetail,
  queryBudgetQuotationTemplateList,
  submitJudge,
  submitOrder,
  updateContract
} from "@/apis/quote-price/following";

const route = useRoute();
const queryId = route.query.ysId;
const templateId = route.query.templateId;
const baseInfo = ref({});
const currTemp = ref({});
provide("currTemp", currTemp);
const tempList = ref({});
const tempDetail = ref({});
const alertDetail = ref({});
const importTempFlag = ref(false);
const editTemplateFlag = ref(false);
const deleteTemplateFlag = ref(false);
const contractModalFlag = ref(false);
const alertDialogFlag = ref(false);
const isFold = ref(false);
const orderVisible = ref(false); // 发起订单
const typeVisible = ref(false); // 合同类型
const contractType = ref(""); // 合同类型
const contractTypeList = ref([]); // 合同类型
const orderForm = ref({
  receivingName: "",
  receivingMobile: "",
  receivingAreaIds: [],
  receivingAreaDetail: [],
  receivingAddress: ""
}); // 发起订单
const area = ref([]); // 发起订单
const formRef = ref(); // 发起订单
const loading = ref({
  baseInfo: false,
  tempList: false,
  tempDetail: false
});
const hasContract = computed(() => tempDetail.value.contractId && tempDetail.value.contractStatus !== 4);
const customerName = computed(() => `${baseInfo.value.customerName || "-"} ${baseInfo.value.customerMobileCode || "-"}`);

//把currTemp写入缓存
const setStorage = () => {
  localStorage.setItem("quotePrice", JSON.stringify({ currTemp: currTemp.value }));
};
const useStorage = (isLoadingDetail = true, isPartView = true) => {
  const quotePrice = localStorage.getItem("quotePrice");
  if (quotePrice) {
    const _currTemp = JSON.parse(quotePrice)?.currTemp;
    const index = tempList.value.findIndex(item => item.budgetId === _currTemp.budgetId);
    if (index >= 0) {
      changeCurrTemp(_currTemp, isLoadingDetail, isPartView);
    } else {
      changeCurrTemp(tempList.value[0], isLoadingDetail, isPartView);
    }
  }
};

const getBaseInfo = async () => {
  loading.value.baseInfo = true;
  // if (!isEmpty(currTemp.value)) {
  const { data } = await getCustomDetail({ ysId: queryId, budgetId: currTemp?.value?.budgetId || 0 });
  baseInfo.value = data;
  // }
  loading.value.baseInfo = false;
};

/**
 * 性能优化，分段渲染
 */
const detailRES = ref({}); //保存一份原始的详情数据，避免分段处理的时候对原始数据造成不可挽回的影响
let timer = null;
const partLenth = 10; //一次切片的列表长度

let partCount = 0;
const nextPart = () => {
  partCount++;
  getPartData(partCount * partLenth, partCount * partLenth + partLenth);
};

const getPartData = (startIndex, endIndex) => {
  tempDetail.value.spaceList = tempDetail.value.spaceList.concat(detailRES.value.spaceList.slice(startIndex, endIndex));
};
const creatTimer = isLoadingDetail => {
  if (timer) clearInterval(timer);
  let count = 0;
  timer = setInterval(() => {
    count++;
    console.log(`第${count}次切片`);
    getPartData(count * partLenth, count * partLenth + partLenth);
    /**分段渲染结束 */
    if (count === Math.ceil(detailRES.value?.spaceList?.length / partLenth) - 1) {
      clearInterval(timer);
      isLoadingDetail && (loading.value.tempDetail = false);
    }
  }, 500);
};
const clearTimer = () => {
  if (timer) clearInterval(timer);
};

/**查询模版的详情数据-数据可能非常多 */
const getTempDetail = async (isLoadingDetail = true, isPartView = true) => {
  console.log("是否分段加载===", isPartView);
  isLoadingDetail && (loading.value.tempDetail = true);
  if (!isEmpty(currTemp.value)) {
    const { data } = await getBudgetDetail({ budgetId: currTemp.value.budgetId });
    detailRES.value = { ...data };

    tempDetail.value = { templateId: currTemp.value.templateId, ...data };
    isLoadingDetail && (loading.value.tempDetail = false);

    // nextTick(() => {
    //   let _data = { ...data };
    //   if (isPartView) {
    //     _data.spaceList = data.spaceList.slice(0, partLenth);
    //     tempDetail.value = { templateId: currTemp.value.templateId, ..._data };
    //   } else {
    //     tempDetail.value = { templateId: currTemp.value.templateId, ...data };
    //   }
    //   if (data.spaceList.length > partLenth && isPartView) {
    //     creatTimer(isLoadingDetail);
    //   } else {
    //     clearTimer();
    //     isLoadingDetail && (loading.value.tempDetail = false);
    //   }
    // });
  } else {
    isLoadingDetail && (loading.value.tempDetail = false);
  }
};

/**查询已导入的模板列表 */
const getTempList = async (selectLast = false, isLoadingDetail = true, isPartView = true) => {
  // loading.value.tempDetail = true;
  const { data } = await queryBudgetQuotationTemplateList({ ysId: queryId });
  tempList.value = data;

  if (data.length > 0) {
    if (selectLast) {
      let index = selectLast ? data.length - 1 : 0;
      currTemp.value = isEmpty(currTemp.value) ? data[index] : currTemp.value;
    } else {
      useStorage(isLoadingDetail, isPartView);
    }
  } else {
    tempDetail.value = {};
  }

  // loading.value.tempDetail = false;
};

const handleSuccessImport = async selectLast => {
  currTemp.value = {};
  await getTempList(selectLast);
  await getTempDetail();
};

const changeCurrTemp = async (item, isLoadingDetail = true, isPartView = true) => {
  partCount = 0;
  currTemp.value = item;
  setStorage(); //把currTemp写入缓存
  await getTempDetail(isLoadingDetail, isPartView); //请求右侧数据
};

const editTemplate = async item => {
  partCount = 0;
  currTemp.value = item;
  setStorage(); //把currTemp写入缓存
  editTemplateFlag.value = true;
  await getTempDetail(false, false); //请求右侧数据
};

const copyTemplate = async item => {
  currTemp.value = item;
  await copyBudgetQuotation({ budgetId: item.budgetId });
  successHandle("模板复制成功");
};

const deleteTemplate = item => {
  currTemp.value = item;
  deleteTemplateFlag.value = true;
};

const deleteTemplateConfirm = async () => {
  await delBudgetQuotation({ budgetId: currTemp.value.budgetId });
  currTemp.value = {};
  successHandle("模板删除成功");
  deleteTemplateFlag.value = false;
};
// 发起订单取消
const handleClose = () => {
  orderVisible.value = false;
};
// 发起订单确认
const handleConfirm = () => {
  formRef.value.validate(async valid => {
    if (valid) {
      await submitOrder(orderForm.value);
      ElMessage.success("提交成功");
      await getTempDetail(false, false);
      await getTempList();
      orderVisible.value = false;
    }
  });
};
// 获取收货地址name
const areaChange = val => {
  orderForm.value.receivingAreaDetail = val.map(val => {
    return findLabelByValue(val, area.value); // 使用递归查找label
  });
};

const findLabelByValue = (value, options) => {
  for (let option of options) {
    if (option.id === value) {
      return option.name; // 找到匹配的label并返回
    } else if (option.children) {
      const found = findLabelByValue(value, option.children); // 递归查找子选项
      if (found) return found; // 如果在子选项中找到，返回该label
    }
  }
  return null; // 如果没有找到，返回null或抛出错误，取决于你的需求
};
onMounted(() => {
  //获取省市区
  getArea().then(res => {
    area.value = res.data;
  });
});
// 提交 发起合同 发起订单
const handleContract = async item => {
  if (item) {
    await changeCurrTemp(item, false, false);
  }
  // 发起订单;
  const { data } = await submitJudge(item ? item.budgetId : tempDetail.value.budgetId);
  if (data === 1) {
    // 纯采购模式
    orderForm.value.budgetId = item ? item.budgetId : tempDetail.value.budgetId;
    orderForm.value.receivingMobile = baseInfo.value.customerMobileCode;
    orderForm.value.receivingName = baseInfo.value.customerName;
    orderForm.value.receivingAreaIds = [];
    orderForm.value.receivingAddress = "";
    orderVisible.value = true;
  } else {
    let type = item ? item.contractType : tempDetail.value.contractType;
    // 非纯采购模式，绑定了合同类型
    if (type) {
      await initiateOrder();
    } else {
      // 非纯采购模式,未绑定合同类型
      contractType.value = "";
      contractTypeList.value = (await getContractTypeList()).data || [];
      typeVisible.value = true;
    }
  }
};
// 关闭订单
const handleCloseContract = async item => {
  ElMessageBox.confirm("是否关闭该订单？", "关闭订单", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    center: true,
    customClass: "message-box",
    cancelButtonClass: "space_cancel_btn",
    confirmButtonClass: "space_confirm_btn",
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        await closeOrder(item ? item.budgetId : tempDetail.value.budgetId);
        ElMessage.success("关闭成功");
        await getTempDetail();
        await getTempList();
        done();
      } else {
        done();
      }
    }
  });
};
// 修改合同
const handleEditContract = () => {
  initiateOrder();
};

const initiateOrder = async () => {
  const { data } = await checkgrossProfitRate({ budgetId: tempDetail.value.budgetId });
  if (data.result) {
    contractModalFlag.value = true;
  } else {
    alertDialogFlag.value = true;
    alertDetail.value = data;
    alertDetail.value.budgetCustomNo = tempDetail.value.budgetCustomNo;
  }
};

// 选择合同类型确认
const handleSubmit = () => {
  // tempDetail.value.contractType = contractType.value;
  typeVisible.value = false;
  initiateOrder();
};
const submitApproval = async () => {
  let { code } = await commitApproval({ budgetId: tempDetail.value.budgetId });
  if (code === 200) alertDialogFlag.value = false;
};

const contractHandle = async item => {
  let apiFn = createContract;
  if (item.contractId && item.status !== 4) apiFn = updateContract;
  else item.contractId && delete item.contractId;
  await apiFn(item);
  successHandle(`合同${item.contractId ? "修改" : "保存"}成功`);
  getTempDetail();
  contractModalFlag.value = false;
};

const successHandle = async message => {
  if (message) ElMessage({ message: message, type: "success" });
  await getTempList(false, true, false);
};

(async () => {
  if (route.query.isPageJump === "true") {
    await getTempList(); //这里的函数会触发getTempDetail()方法;
    currTemp.value = tempList.value.find(item => item.budgetId === route.query.budgetId);
    const element = document.getElementById(currTemp.value.budgetId);
    element.scrollIntoView({ behavior: "smooth", block: "center" });
    nextTick(() => {
      setTimeout(() => {
        console.log("模拟点击");
        changeCurrTemp(currTemp.value);
      }, 500);
    });
  } else {
    await getTempList(); //这里的函数会触发getTempDetail()方法;
    if (templateId) {
      currTemp.value = tempList.value.find(item => item.templateId === templateId);
    }
  }

  getBaseInfo();
  // getTempDetail();
})();
</script>

<style lang="scss">
.following_list {
  height: calc(100% - 114px);
  margin-top: 114px;
  overflow: hidden;

  .fixed-fold-btn {
    width: 15px;
    height: 34px;
    position: fixed;
    left: 6px;
    top: 146px;
    cursor: pointer;
    background: url("@/assets/images/fold-right.png");
    background-size: 100% 100%;

    &.fold-left {
      background: url("@/assets/images/fold-left.png");
      background-size: 100% 100%;
    }
  }

  .content {
    width: 100%;
    height: 100%;
    padding: 20px 15px 15px 20px;
    box-sizing: border-box;

    .content_box {
      width: 100%;
      height: 100%;
      background: white;
      border-radius: 10px;
      display: grid;
      grid-template-columns: 280px calc(100% - 280px);
      transition: all 0.3s;

      .content_left {
        border-right: 1px solid #e1e6ed;
        display: grid;
        grid-template-rows: 255px calc(100% - 255px);
        overflow: hidden;

        .left_info {
          border-bottom: 1px solid #e1e6ed;
          padding: 20px;

          .info_title {
            color: #4e5969;
            font-size: 16px;
          }

          .info_detail {
            display: grid;
            grid-template-columns: 85px 1fr;
            color: #86909c;
            gap: 24px 0;
            padding: 14px 0;

            .detail_text {
              color: #3d3d3d;
              text-overflow: ellipsis;
              overflow: hidden;
              white-space: nowrap;
            }
          }
        }

        .left_template {
          .template_title {
            color: #4e5969;
            font-size: 16px;
            padding: 20px;
            line-height: 24px;
            display: flex;
            justify-content: space-between;
          }

          .template_list {
            height: calc(100% - 80px);
            display: grid;
            gap: 20px;
            padding: 0 16px 16px;
            overflow: auto;
            grid-template-rows: repeat(auto-fill, minmax(69px, 1fr));

            .list_box {
              box-sizing: border-box;
              width: 100%;
              height: 70px;
              box-shadow: 0px 0px 10px 0px #86909c19;
              background: #ebeef1;
              border-radius: 10px;
              padding: 8px 16px;
              position: relative;

              .box_suffix {
                position: absolute;
                right: 0;
                top: 0;
                font-size: 12px;
                line-height: 24px;
                padding: 0 15px;
                background: #ffc86a;
                border-radius: 0 8px;
              }

              .box_title {
                line-height: 30px;
                color: #191919;
                width: 170px;

                & > p {
                  max-width: 130px;
                }
              }

              .box_content {
                display: flex;
                justify-content: space-between;
                font-size: 12px;
                line-height: 24px;
                color: #86909c;
              }
            }

            .active_box {
              background: #424e66;

              .box_title {
                line-height: 30px;
                color: white;
              }
            }
          }
        }
      }

      .content_right {
        height: 100%;
        overflow: auto;
      }

      &.fold-wrap {
        grid-template-columns: 0px calc(100% - 0px);
        transition: all 0.3s;

        .content_left {
          border-right: none;
        }
      }
    }
  }
}

.space_cancel_btn {
  width: 100px;
  border-radius: 2px !important;
  border: 0 !important;
  background: #f2f3f5 !important;
  color: black !important;
}

.space_confirm_btn {
  width: 100px;
  border-radius: 2px !important;
  border: 0 !important;
  background: #424e66 !important;
}

.space_cancel_btn {
  width: 100px;
  border-radius: 2px !important;
  border: 0 !important;
  background: #f2f3f5 !important;
  color: black !important;
}

.space_confirm_btn {
  width: 100px;
  border-radius: 2px !important;
  border: 0 !important;
  background: #424e66 !important;
}
</style>
